package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
)

func upload_server(conn net.Conn, fileInfo string) {
	// 文件名
	fileName := strings.Split(fileInfo, " ")[2]
	fmt.Println(fileName)
	// 上传文件的路径
	f, _ := os.OpenFile("C:\\Users\\Bai'mo\\Desktop\\"+fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
	writer := bufio.NewWriter(f)
	defer f.Close()

	// 文件大小
	fileSizeStr := strings.Split(fileInfo, " ")[3]
	fileSize, _ := strconv.Atoi(fileSizeStr)

	writeSize := 0
	for writeSize < fileSize {
		data := make([]byte, 1024)
		n, _ := conn.Read(data)
		writer.WriteString(string(data[:n]))
		writer.Flush()
		writeSize += n
	}
	fmt.Println("上传成功！")

}
func down_server() {

}

func main() {
	// 建立socket
	sock, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("start...")
	defer sock.Close()

	for {
		// 创建连接管道
		conn, err := sock.Accept() // 阻塞
		defer conn.Close()
		if err != nil {
			fmt.Println(err)
			break
		}

		// 读取文件信息
		fileInfoBytes := make([]byte, 1024)
		n, err := conn.Read(fileInfoBytes)

		fileInfo := string(fileInfoBytes[:n])

		cmd := strings.Split(fileInfo, " ")[0]
		fmt.Println(fileInfo)
		fmt.Println("read///", cmd)
		switch cmd {
		case "put":
			upload_server(conn, fileInfo)
		case "down":
			down_server()
		}
	}
}
